package com.wonderland.lucy.security.shiro;

import com.wonderland.lucy.jedis.JedisTempalte;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class RedisCacheManager implements CacheManager {

	private JedisTempalte jedisTempalte;

	public void setJedisTempalte(JedisTempalte jedisTempalte) {
		this.jedisTempalte = jedisTempalte;
	}

	private static final Logger logger = LoggerFactory
			.getLogger(RedisCacheManager.class);

	// fast lookup by name map
	private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

	/**
	 * The Redis key prefix for caches 
	 */
	private String keyPrefix = JedisSessionDao.KEY_PREFIX;
	
	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}
	
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		logger.debug("获取名称为: " + name + " 的RedisCache实例");
		
		Cache c = caches.get(name);
		
		if (c == null) {

			// create a new cache instance
			c = new RedisCache<K, V>(jedisTempalte, keyPrefix);
			
			// add it to the cache collection
			caches.put(name, c);
		}
		return c;
	}
}
